package com.dm.contriller;



import com.alibaba.fastjson.JSONObject;
import com.dm.common.KafKaUtil;
import com.dm.vo.TokenVO;

import com.dm.common.Constants;
import com.dm.common.EmptyUtils;
import com.dm.common.RedisUtils;
import com.dm.dto.Dto;
import com.dm.dto.DtoUtil;
import com.dm.exception.ErrorCode;
import com.dm.vo.DmUserVO;

import com.dm.client.dm_user.RestDmUserClient;
import com.dm.pojo.dm_user.DmUser;
import com.dm.service.use_token.TokenService;
import com.dm.service.user_login.LoginDmUser;



import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping(value = "/user/api")
public class UserLoginController {

    @Resource
    private LoginDmUser loginDmUser;
    @Resource
    private TokenService tokenService;
    @Resource
    private RestDmUserClient restDmUserClient;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private KafKaUtil kafKaUtil;

    /**
     * 用户登录
     *
     * @param phone
     * @param password
     * @param vcode
     * @return
     */
    @RequestMapping(value = "/v/login", method = RequestMethod.POST)
    public Dto userLogin(
            @RequestParam(value = "phone", required = true) String phone,
            @RequestParam(value = "password", required = false)String password,
            @RequestParam(value = "vcode", required = false) String vcode) throws Exception {
        String tokenKey = null;
        Map<String,Object> map=new HashMap<>();
        Integer count=null;
        String ma=null;
        DmUserVO dmUserVO=null;



        if(EmptyUtils.isNotEmpty(phone)&&EmptyUtils.isEmpty(password)&&EmptyUtils.isEmpty(vcode)){
        //============================手机验证码发送===========================
        //=====1手机号格式是否正确
            if(loginDmUser.validPhon(phone)){
                //=====2正确的话判断是否未注册
                map.put("phone",phone);
                count=restDmUserClient.getDmUserCountByMap(map);
                if(count<0){
                    //未注册返回异常消息
                    return  DtoUtil.returnFail(ErrorCode.PHONE_NO_REGISTER.getErrorMessage(),ErrorCode.PHONE_NO_REGISTER.getErrorCode());
                }else{
                    try {
                        //=====3发送验证码并且判断验证码是否在有效期
                        //存在有效期
                        if(redisUtils.exist(Constants.LoginAndRegisterCode.login+phone)){
                            //异常消息
                            return DtoUtil.returnFail(ErrorCode.ONE_60_SECOND.getErrorMessage(),ErrorCode.ONE_60_SECOND.getErrorCode());
                        }
                        //发送验证码
                        ma=loginDmUser.sendPhon(Constants.LoginAndRegisterCode.login,phone);
                        return DtoUtil.returnSuccess(ErrorCode.VERIFICATION_SEND.getErrorMessage(),ma);
                    }catch (Exception e){
                        //发送验证码时的异常捕捉
                        return DtoUtil.returnFail(ErrorCode.VERIFICATION_SEND_ERROR.getErrorMessage(),ErrorCode.VERIFICATION_SEND_ERROR.getErrorCode());
                    }
                }
            }



        }else if(EmptyUtils.isNotEmpty(phone)&&EmptyUtils.isEmpty(password)&&EmptyUtils.isNotEmpty(vcode)){
            //============================手机验证码登录===========================
            //=====1：验证码验证
            if(redisUtils.exist(Constants.LoginAndRegisterCode.login+phone)){
                //获取redis的验证码
                ma=redisUtils.get(Constants.LoginAndRegisterCode.login+phone).toString();
            }else{
                ma=null;
            }
             if(vcode.equals(ma)){
                //=====1；成功
                //根据手机号获取用户信息
                dmUserVO = loginDmUser.queryUser_PhoneAndPassword(phone, null);
                //判断有无token
                tokenKey = tokenService.validateToken(dmUserVO.getUserId().toString());
                //无token
                if (EmptyUtils.isEmpty(tokenKey)) {
                    //=====1:生成token并储存redis
                    //生成token
                    tokenKey = tokenService.getToken("PC", dmUserVO);
                    //储存token
                    tokenService.saveTokenById(dmUserVO.getUserId().toString(), tokenKey);
                    tokenService.saveToken(tokenKey, dmUserVO);
                }
            }else if(!vcode.equals(ma)){
                //=====2：失败
                return DtoUtil.returnFail(ErrorCode.CODE_ERROR.getErrorMessage(),ErrorCode.CODE_ERROR.getErrorCode());
            }





        }else if(EmptyUtils.isNotEmpty(phone)&&EmptyUtils.isNotEmpty(password)&&EmptyUtils.isEmpty(vcode)) {

            //============================手机和密码登录===========================
            //=====1:获取用户相关信息
             dmUserVO = loginDmUser.queryUser_PhoneAndPassword(phone, password);
            //=====2：登录失败
            if (EmptyUtils.isEmpty(dmUserVO)) {
                //kafKaUtil.sendInfoMessage("登录失败！");
                return DtoUtil.returnFail(ErrorCode.PHONE_AND_PASSWORD_ERROR.getErrorMessage(), ErrorCode.PHONE_AND_PASSWORD_ERROR.getErrorCode());

            } else {
                //=====3：登录成功
                //=====1：判断有无token
                tokenKey = tokenService.validateToken(dmUserVO.getUserId().toString());
                //无token
                if (EmptyUtils.isEmpty(tokenKey)) {
                    //=====1:生成token并储存redis
                    //生成token
                    tokenKey = tokenService.getToken("PC", dmUserVO);
                    //储存token
                    tokenService.saveTokenById(dmUserVO.getUserId().toString(), tokenKey);
                    tokenService.saveToken(tokenKey, dmUserVO);
                }
            }
        }

            //返回用户信息和token到客户端
            return DtoUtil.returnSuccess(ErrorCode.LOGIN_SUCCESS.getErrorMessage(),loginDmUser.mergeByUser_Token(tokenKey, dmUserVO));

    }


    /**
     * 用户退出
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/v/loginOut", method = RequestMethod.POST)
    public Dto outLogin(@RequestParam(value = "token", required = true) String token) throws Exception {
        //=========判断token是否过期
        String tokenValue = tokenService.validateToken(token);
        DmUserVO dmUser = JSONObject.parseObject(tokenValue, DmUserVO.class);
        if (EmptyUtils.isNotEmpty(tokenValue)) {
            //执行退出
            tokenService.deleteToken(token);
            tokenService.deleteToken(dmUser.getUserId().toString());
            //如果有其他业务数据，也需要销毁，未完待续
            //。。。。。。。。
            return DtoUtil.returnSuccess();
        } else {
            //kafKaUtil.sendInfoMessage("会话失效");
            return DtoUtil.returnFail(ErrorCode.TOKEN_NO.getErrorMessage(), ErrorCode.TOKEN_NO.getErrorCode());
        }
    }

/**
 * 刷新Token(输入参数删除了手机号)
 *
 * @param token
 * @return
 */
    @RequestMapping(value = "/v/replaceToken", method = RequestMethod.POST)
    public Dto replaceToken(@RequestParam(value = "token", required = true) String token) throws Exception {
    String tokenVal=null;

        DmUserVO dmUserVO=null;
        TokenVO tokenVO=null;
        Long expireToken=null;
        Long thisTime=null;
        String tokenKey=null;
        //====1：验证用户是否登录
        if(!redisUtils.exist(token)){
            //=====1：未登录
            return DtoUtil.returnFail(ErrorCode.USER_NO_LOGIN.getErrorMessage(),ErrorCode.USER_NO_LOGIN.getErrorCode());
        }else{
            //=====2：是登录
            //获取token并转为用户对象
            tokenVal=redisUtils.get(token).toString();
            dmUserVO=JSONObject.parseObject(tokenVal,DmUserVO.class);
                //=====1：判断token置换周期是否到期
            //token到期时间
            expireToken=redisUtils.getExpire(token);
            if(expireToken<=Constants.Redis_Expire.REPLACEMENT_DELAY) {
                //=====1：到期
                    //=====1：删除旧token，删除新的token
                tokenService.deleteToken(token);
                tokenService.deleteToken(dmUserVO.getUserId().toString());
                //生成token
                tokenKey = tokenService.getToken("PC", dmUserVO);
                //储存token
                tokenService.saveTokenById(dmUserVO.getUserId().toString(), tokenKey);
                tokenService.saveToken(tokenKey, dmUserVO);
                return DtoUtil.returnSuccess(ErrorCode.RESET_SUCCESS.getErrorMessage(),loginDmUser.mergeByUser_Token(tokenKey, dmUserVO));
            }

        }
        //=====2：未到期
        return DtoUtil.returnFail(ErrorCode.TOKEN_RESET_TIME_NO.getErrorMessage(),ErrorCode.TOKEN_RESET_TIME_NO.getErrorCode());
            }
    /**
     * 根据token获取用户信息
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/v/loadCurrentUserByToken", method = RequestMethod.POST)
    public Dto loadCurrentUserByToken(@RequestParam(value = "token", required = true) String token) throws Exception {
        String tokenVal=null;
        //根据token获取用户信息和token值
            tokenVal = redisUtils.get(token).toString();
            //转换json数组对象
        DmUserVO ob=JSONObject.parseObject(tokenVal,DmUserVO.class);
            return DtoUtil.returnDataSuccess(ob);

    }


    }
